package com.league.blog.controller;

import com.league.blog.mapper.ArticleMapper;
import com.league.blog.mapper.UserMapper;
import com.league.blog.pojo.ArticleWithBLOBs;
import com.league.blog.pojo.User;
import com.league.blog.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author 黄豪琦
 * 日期:2020-03-30 14:24
 * 说明:
 */
@Controller
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    private ArticleMapper articleMapper;

    private UserMapper userMapper;

    @RequestMapping("/detail/{articleCode}")
    public String showArticle(@PathVariable("articleCode") String articleCode, Model model) {

        if (articleCode == null || StringUtils.isBlank(articleCode)) {
            return "redirect:/";
        } else {
            ArticleWithBLOBs article = articleMapper.selectByArticleCode(articleCode);
            if (article != null) {
                article.setCreateTime(StringUtils.formatDate(article.getCreateTime()));
                article.setEditorTime(StringUtils.formatDate(article.getEditorTime()));
                model.addAttribute("article", article);

                User author = userMapper.selectByPrimaryKey(article.getUserId());
                model.addAttribute("author", author);
            } else {
                log.error("一个错误的文章代码：[" + articleCode + "]，并没有这篇文章或者已被删除。");
                return "common/404";
            }
        }
        return "detail";
    }

    @Autowired
    public void setArticleMapper(ArticleMapper articleMapper) {
        this.articleMapper = articleMapper;
    }

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }
}
